//
//  OMPreviewController.m
//  Weibbo
//
//  Created by lilg on 13-6-16.
//  Copyright (c) 2013年 Omnivores. All rights reserved.
//

#import "OMPreviewController.h"
#import "OMShareViewController.h"
#import "TSPopoverController.h"
#import "FMMoveTableView.h"
#import "PreViewCell.h"
#import "PreHeadView.h"
#import "UIViewAdditions.h"
#import "OMEditViewController.h"
#import "DraftItem.h"
#import "UIViewAdditions.h"
#import "SnapView.h"


@interface OMPreviewController ()<PreHeadViewDelegate,FMMoveTableViewDataSource,FMMoveTableViewDelegate,RMSwipeTableViewCellDelegate,ShareViewControllerDelegate,OMEditViewControllerDelegate>
{
    TSPopoverController *popoverController;
    UIButton  *aliginedButton;
    
    BOOL  _isAliginChanged;
    BOOL  _isExpand;
}

@property (nonatomic,retain)id grabbedObject;
@property (nonatomic, retain)PreHeadView *headView;
@property (nonatomic, retain)FMMoveTableView *myTableView;
@property (nonatomic,retain)UITableViewCell  *preAliginedCell;
@end

@implementation OMPreviewController
@synthesize preAliginedCell;
@synthesize myTableView;
@synthesize grabbedObject;
@synthesize dismiss;
@synthesize headView;
@synthesize entity;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        _isExpand = NO;
//        UIImageView  *frameImage = [[UIImageView alloc] initWithFrame:CGRectMake(-20, -25, 360, (int)(1.08 * SCREEN_HEIGHT))];
//        [frameImage setImage:[UIImage imageNamed:@"frame.png"]];
//        [frameImage setTag:9999];
//        [self.view addSubview:frameImage];
//        [frameImage release];
        
        
        myTableView = [[FMMoveTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 20) style:UITableViewStylePlain];
        [myTableView setBackgroundView:nil];
        myTableView.dataSource = self;
        myTableView.delegate = self;
        headView=[[PreHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 222)];
        headView.delegate = self;
        myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [myTableView setTableFooterView:[self tableViewFooter]];
        [headView setDraftEntity:[WBBDRAFT draftAtIndex:self.view.tag]];
        myTableView.tableHeaderView = headView;
        [self.view addSubview:myTableView];
        
        homeBarView = [[OMHomeBarView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT- 20 - 51,SCREEN_WIDTH, 51) Delegate:self];
        [self.view addSubview:homeBarView];
        
        aliginedButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        [aliginedButton addTarget:self action:@selector(myTableViewIsExpend) forControlEvents:UIControlEventTouchUpInside];
        [aliginedButton setFrame:CGRectMake(SCREEN_WIDTH - 40, SCREEN_HEIGHT/2, 30, 60)];
        [self.view addSubview:aliginedButton];
  }
    return self;
}

- (void)viewDidLoad
{
  [super viewDidLoad];
}


- (void)viewDidUnload
{
    UIRelease(popoverController);
    UIRelease(homeBarView);
    UIRelease(myTableView);
    UIRelease(headView);
    UIRelease(aliginedButton);
    [super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    UIRelease(popoverController);
    UIRelease(homeBarView);
    UIRelease(myTableView);
    UIRelease(headView);
    UIRelease(preAliginedCell);
    UIRelease(aliginedButton);
    [super dealloc];
}

- (void)setPreviewStyle:(BOOL)flag;
{
    [aliginedButton setHidden:flag];
    [homeBarView setHidden:flag];    
}

- (void)setDraft:(DraftEntity *)draftEntiry
{
    self.entity =draftEntiry;
    [myTableView reloadData];
    
    [headView setDraftEntity:draftEntiry];

}

//预览图片
-(void)myTableViewIsExpend
{
//    [homeBarView SetUserInteractionEnabled:_isExpand];
    _isExpand = !_isExpand;
    NSArray *indexPathArr = [myTableView indexPathsForVisibleRows];
    [myTableView reloadRowsAtIndexPaths:indexPathArr withRowAnimation:UITableViewRowAnimationFade];
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.entity count];
}

- (UITableViewCell *)tableView:(FMMoveTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *preViewCellIdentifier = @"PreViewCell";
        PreViewCell *preViewCell = [tableView dequeueReusableCellWithIdentifier:preViewCellIdentifier];
        if (preViewCell == nil)
        {
            preViewCell = [[[PreViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:preViewCellIdentifier]autorelease];
            preViewCell.delegate=self;
        }
        /******************************** NOTE ********************************
         * Implement this check in your table view data source to ensure that the moving
         * row's content is reseted
         **********************************************************************/
        if ([tableView indexPathIsMovingIndexPath:indexPath])
        {
            [preViewCell prepareForMove];
        }
        else
        {
            [preViewCell setDraftItemInfo:[self.entity.draftList objectAtIndex:indexPath.row] IsExpand:_isExpand];
            [preViewCell setShouldIndentWhileEditing:NO];
            [preViewCell setShowsReorderControl:NO];
        }
        return preViewCell;
}

- (CGFloat)tableView:(FMMoveTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row<[self.entity count]) {
        return [PreViewCell heightForItem:[self.entity.draftList objectAtIndex:indexPath.row] IsExpand:_isExpand];
    }
    else
    {
        return CellHeight;
    }
}

-(UIView *)tableViewFooter
{
    UIView *footView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CellHeight*3)]autorelease];
    footView.backgroundColor = UIWhiteColor;
    UILabel *creatLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 15)];
    creatLab.textColor = UIDarkGrayColor;
    creatLab.backgroundColor = UIClearColor;
    creatLab.textAlignment = NSTextAlignmentCenter;
    creatLab.font = [UIFont systemFontOfSize:13];
    DraftEntity *tmp = [WBBDRAFT draftAtIndex:self.view.tag];
    NSString *creattimeStr = [self getDateyyyyMMddHHmmssString:[NSDate dateWithTimeIntervalSince1970:tmp.createTime]];
    NSString *modifySinceLasttimeStr = [self compareCurrentTime:[NSDate dateWithTimeIntervalSince1970:tmp.modifyTime]];
    [ creatLab setText:[NSString stringWithFormat:@"Created:%@ | Edited:%@",creattimeStr,modifySinceLasttimeStr]];
    [footView addSubview:creatLab];
    [creatLab release];
    return footView;
}

- (void)moveTableView:(FMMoveTableView *)tableView moveRowFromIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    DraftItem *item = [[self.entity.draftList objectAtIndex:fromIndexPath.row]retain];
    [self.entity.draftList removeObjectAtIndex:fromIndexPath.row];
    [self.entity.draftList insertObject:item atIndex:toIndexPath.row];
    [item release];
}


- (NSIndexPath *)moveTableView:(FMMoveTableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
	if ([sourceIndexPath section] != [proposedDestinationIndexPath section]) {
		proposedDestinationIndexPath = sourceIndexPath;
	}
	return proposedDestinationIndexPath;
}



#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        DraftItem  *tmpItem = [self.entity.draftList objectAtIndex:indexPath.row];
        if ([tmpItem isImage])
        {
            OMPhotoViewController *photoViewController = [[OMPhotoViewController alloc]initWithCurselectCell:indexPath.row];
            photoViewController.delegate =self;
            [ROOT_VIEWCONTROLLER pushViewController:photoViewController animated:YES];
            [photoViewController release];
        }
        else
        {
            if (![tmpItem isQuotation]) {
                OMEditViewController *richtextViewController = [[OMEditViewController alloc]initWithIndex:indexPath.row richText:tmpItem.text];
                richtextViewController.delegate = self;
                [ROOT_VIEWCONTROLLER pushViewController:richtextViewController animated:YES];
                [richtextViewController release];
            }
        }
}

#pragma mark - Swipe Table View Cell Delegate


-(void)swipeTableViewCellWillResetState:(PreViewCell *)swipeTableViewCell fromPoint:(CGPoint)point animation:(UIViewAnimationOptions)animation velocity:(CGPoint)velocity {
    if (point.x >= EffectiveDistance(swipeTableViewCell.frame)) {
        //待修改
        NSIndexPath *indexPath = [self.myTableView indexPathForCell:swipeTableViewCell];
        DraftItem *item = [self.entity.draftList objectAtIndex:indexPath.row];
        if (item.isQuotation) item.isQuotation = NO;
        else item.isQuotation = YES;
        [self.entity synchronise];
        [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [(PreViewCell*)swipeTableViewCell setFavourite:item.isQuotation  animated:YES];
    }
    else if (point.x < 0 && -point.x >= EffectiveDistance(swipeTableViewCell.frame)) {
        swipeTableViewCell.shouldAnimateCellReset = NO;
        [[(PreViewCell*)swipeTableViewCell checkmarkGreyImageView] removeFromSuperview];
        [UIView animateWithDuration:0.25
                              delay:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             CGRect frame = swipeTableViewCell.contentView.frame;
                             frame.origin.x=-frame.size.width;
                             swipeTableViewCell.contentView.frame = frame;
                         }
                         completion:^(BOOL finished) {
                             if (finished) {
                                 [swipeTableViewCell.contentView setHidden:YES];
                                 NSIndexPath *indexPath = [myTableView indexPathForCell:swipeTableViewCell];
                                 [self.entity.draftList removeObjectAtIndex:indexPath.row];
                                 [myTableView beginUpdates];
                                 [myTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                                 [myTableView endUpdates];
                                 [self.entity synchronise];
                             }
                         }
         ];
    }
}

-(void)swipeTableViewCellDidResetState:(PreViewCell *)swipeTableViewCell fromPoint:(CGPoint)point animation:(UIViewAnimationOptions)animation velocity:(CGPoint)velocity {
}


-(void)OMEditViewControllerDelegate:(NSInteger)cellNum NSAttributedString:(NSAttributedString *)AttributedString
{
    if ([AttributedString string].length == 0) {
        return;
    }
    if (cellNum == -1) {
        DraftItem *item = [[DraftItem alloc]init];
        [item setText:[AttributedString mutableCopy]];
        [[self.entity draftList] addObject:item];
        [item release];
    }else{
        DraftItem *item = [self.entity.draftList objectAtIndex:cellNum];
        [item setText:[AttributedString mutableCopy]];
    }

    [myTableView reloadData];
    [self.entity synchronise];
}

#pragma mark - PreHeadViewDelegate method

-(void)PreHeadViewDelegateUpDateTitleText:(NSString *)text
{
    [self.entity setTitleText:text];
    [WBBDRAFT replaceDraft:self.entity index:self.view.tag];
}
#pragma mark - OMHomeBarViewDelegate method
-(void)OMHomeBarViewDelegate:(id)sender
{
    switch ([sender tag]) {
        case OMHomeBarClickEvent_Back:
        {
//            if ( [[myTableView visibleCells] count]>2) {
                //如果有可用的Cell则将第一个cell滚到中间
                _isExpand = NO;
                [myTableView setContentOffset:CGPointMake(0, 0)];
                [myTableView reloadData];

//                NSIndexPath *idxPath = [NSIndexPath indexPathForRow:0 inSection:0];
//                [myTableView scrollToRowAtIndexPath:idxPath
//                                   atScrollPosition:UITableViewScrollPositionMiddle
//                                           animated:NO];
//            }
            [self setPreviewStyle:YES];
            if (self.dismiss) {
                self.dismiss();
            }
        }
            break;
        case OMHomeBarClickEvent_AddWord:
        {
            NSMutableAttributedString *stringAttri = [[[NSMutableAttributedString alloc]initWithString:@""] autorelease];
            
            OMEditViewController *richtextViewController = [[OMEditViewController alloc]initWithIndex:-1 richText:stringAttri];
            richtextViewController.delegate = self;
            [ROOT_VIEWCONTROLLER pushViewController:richtextViewController animated:YES];
            [richtextViewController release];
        }
            break;
        case OMHomeBarClickEvent_AddImage:
        {
            OMPhotoViewController *photoViewController = [[OMPhotoViewController alloc]initWithCurselectCell:-1];
            photoViewController.delegate =self;
            [ROOT_VIEWCONTROLLER pushViewController:photoViewController animated:YES];
            [photoViewController release];
            
        }
            break;
        case OMHomeBarClickEvent_Share:
        {
            OMShareViewController *shareController = [[OMShareViewController alloc]initWithNibName:nil bundle:nil];
            shareController.delegate = self;
            shareController.view.frame = CGRectMake(0, 0, 250, 222);
            shareController.shareImage = [SnapView imageWithEntity:self.entity];
            popoverController = [[TSPopoverController alloc] initWithContentViewController:shareController];
            [shareController release];
            popoverController.popoverBaseColor = [UIColor whiteColor];
            popoverController.popoverGradient= NO;
            popoverController.arrowPosition = TSPopoverArrowPositionVertical;
            [popoverController showPopoverWithTouch:sender];
            
            
//            UIImage  *img = [SnapView imageWithEntity:self.entity];
//            
//            UIImageView  *bkView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
//            [bkView setContentMode:UIViewContentModeTopLeft];
//            [bkView setImage:img];
//            [self.view addSubview:bkView];

        }
            break;
        default:
            break;
    }
}

#pragma mark  ------ScrollView  Delegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [UIView beginAnimations:@"" context:@""];
    [UIView setAnimationDuration:0.5f];
    [homeBarView setTop:SCREEN_HEIGHT];
    [UIView commitAnimations];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (decelerate) {
        [self performSelector:@selector(ShowHomeBar) withObject:nil afterDelay:0];
    }
    else
    {
        [self ShowHomeBar];
    }
}

//显示下面的Bar
-(void)ShowHomeBar
{
    [UIView beginAnimations:@"" context:@""];
    [UIView setAnimationDuration:0.5f];
    [homeBarView setTop:SCREEN_HEIGHT-20-51];
    [UIView commitAnimations];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([self.entity.draftList count] == 0) {
        return;
    }
    if (scrollView == myTableView)
    {
        float  center = [self aliginedCell];
        if (_isAliginChanged) {
            [UIView beginAnimations:@"" context:@""];
            [UIView setAnimationDuration:0.5f];
            [aliginedButton setTop:center];
            [UIView commitAnimations];
        }else{
            [aliginedButton setTop:center];
        }
    }
}

- (float)aliginedCell
{
    NSArray  *visiableCell = [myTableView visibleCells];
    for(UITableViewCell  *cell in visiableCell)
    {
        NSIndexPath  *indexPath = [myTableView indexPathForCell:cell];
        CGRect cellRect = [myTableView rectForRowAtIndexPath:indexPath];
        cellRect = CGRectMake(cellRect.origin.x - myTableView.contentOffset.x, cellRect.origin.y - myTableView.contentOffset.y, cellRect.size.width, cellRect.size.height);
        float y  = cellRect.origin.y;
        float maxY = cellRect.size.height + cellRect.origin.y;
        float center = (SCREEN_HEIGHT - 44 - 20)/2.0f;
        if (y< center && center < maxY)
        {
            if (self.preAliginedCell != cell) {
                _isAliginChanged = YES;
            }else{
                _isAliginChanged = NO;
            }
            self.preAliginedCell = cell;
            return cellRect.size.height/2.0f + y - 30;
        }
    }
    CGRect cellRect = [myTableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    cellRect = CGRectMake(cellRect.origin.x - myTableView.contentOffset.x, cellRect.origin.y - myTableView.contentOffset.y, cellRect.size.width, cellRect.size.height);
    float y  = cellRect.origin.y;
    return cellRect.size.height/2.0f + y - 30;
}
#pragma mark  ShareViewControllerDelegate
-(void)ShareViewDidDismiss
{
    [popoverController dismissPopoverAnimatd:YES];
}

#pragma mark - PhotoViewDelegate method
-(void)PhotoViewDelegateDidFinishedPhoto:(UIImage *)image index:(NSInteger)index
{
    if (index == -1) {
        DraftItem *item = [[DraftItem alloc]init];
        [item setImage:image];
        [[self.entity draftList] addObject:item];
        [item release];
    }else{
        DraftItem *item = [self.entity.draftList objectAtIndex:index];
        [item setImage:image];
    }

    
    [self.entity synchronise];
    [myTableView reloadData];
    
}

-(void)PhotoViewDelegateCancelPhotoindex:(NSInteger)index
{
    NSLog(@"PhotoViewDelegateCancelPhoto");
}


/**
* 计算指定时间与当前的时间差
* @param compareDate   某一指定时间
* @return 多少(秒or分or天or月or年)+前 (比如，3天前、10分钟前)
*/
-(NSString *) compareCurrentTime:(NSDate*) compareDate
{
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    int temp = 0;
    NSString *result;
    if (timeInterval < 60) {
    result = @"secs ago";
    }
    else if((temp = timeInterval/60) <60){
    result = @"mins ago";
    }

    else if((temp = temp/60) <24){
    result = @"hours ago";
    }

    else if((temp = temp/24) <30){
    result = @"days ago";
    }

    else if((temp = temp/30) <12){
    result = @"months ago";
    }
    else{
    temp = temp/12;
    result = @"years ago";
    }

    return  result;
}


- (NSString *) getDateyyyyMMddHHmmssString:(NSDate *) date
{
    return [self getDateString:date withFormat:@"yyyy-MM-dd , HH:mm"];
}

- (NSString *) getDateString:(NSDate *) date withFormat:(NSString *) format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *locale = [NSLocale currentLocale];
    [dateFormatter setLocale:locale];
    [dateFormatter setDateFormat:format];
    NSString *dateStr = [NSString stringWithString:[dateFormatter stringFromDate:date]];
    
    return dateStr;
}

@end
